package com.wyl.netty.server;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.wyl.netty.common.protobuf.MessageModule;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author: wyl
 * @date: 2021/7/13
 * @des:
 * 不需要spring管理，因为会阻塞springboot启动流程，单独的服务
 * tomcat启动后，启动本Server
 */
public class Server {

    public static final int PORT = 8888;

    public Server(){
        // 配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        try {
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //快速复用端口
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //缓存区 池化操作
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws IOException {
                            ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                            ch.pipeline().addLast(new ProtobufDecoder(MessageModule.Message.getDefaultInstance()));
                            ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                            ch.pipeline().addLast(new ProtobufEncoder());

                            // ====================== 增加心跳支持 start    ======================
                            // 针对客户端，如果在30秒没有向服务端发送读写心跳(ALL)，则主动断开
                            // 如果是读空闲或者写空闲，不处理,读写空闲超过30秒，则断开连接
                            ch.pipeline().addLast(new IdleStateHandler(0, 0, 30, TimeUnit.SECONDS));
                            // 自定义的空闲状态检测
                            ch.pipeline().addLast(new HeartBeatHandler());
                            // ====================== 增加心跳支持 end    ======================

                            ch.pipeline().addLast(new ServerHandler());
                        }
                    });

            // 	绑定端口，同步等待成功
            ChannelFuture cf = b.bind(PORT).sync();

            System.out.println(" Server startup.. port: " + PORT);
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println(" Server shutdown.. ");
        }
    }
}
